<template>
  <el-dialog
    :visible.sync="show"
    custom-class="selectTestletDialog"
    @close="handleClose"
    title="选择题组"
    :lock-scroll="true"
  >
    <div class="container">
      <div class="toolsBox">
        <div>
          <!-- <el-button class="newTestletBtn" @click="handleShowQuestionBankIframe"
            >新建题组</el-button
          > -->
          <el-button class="saveBtn" @click="handleSaveTestLet">保存</el-button>
          <!-- 标签搜索 暂无此功能 -->
          <!-- <div class="selectBox">
            <el-select
              v-model="selectType"
              multiple
              filterable
              allow-create
              collapse-tags
              default-first-option
              placeholder="暂无可选标签"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div> -->
        </div>
        <div class="searchInputBox">
          <el-input
            v-model="searchValue"
            placeholder="请输入关键词"
            class="searchInput"
          ></el-input>
          <el-button class="searchBtn">搜索</el-button>
        </div>
      </div>
      <div class="testletList">
        <el-table
          :data="testLets"
          style="width: 100%"
          ref="table"
          max-height="400"
          :border="true"
          highlight-current-row
          :row-key="getRowKeys"
          :expand-row-keys="expands"
          @selection-change="handleSelectionChange"
          @expand-change="handleExpandChange"
          @row-click="handleRowClick"
          @current-change="handleCurrentRowChange"
        >
          >
          <el-table-column
            label="ID"
            prop="gid"
            align="center"
            width="100"
            min-width="100"
          />
          <el-table-column
            label="题组名称"
            prop="title"
            align="center"
            class-name="testTelName"
          />
          <el-table-column
            label="单次刷题次数"
            prop="one_time"
            align="center"
            width="90"
            min-width="90"
          />
          <el-table-column
            type="expand"
            label="查看详情"
            align="center"
            width="100"
          >
            <template slot-scope="props">
              <div
                v-loading="props.row.load"
                element-loading-text="正在加载中"
                element-loading-spinner="el-icon-loading"
              >
                <div
                  class="subjectList"
                  v-if="props.row.childrens && props.row.childrens.length"
                >
                  <div
                    style="padding: 10px 0 5px"
                    v-for="(item, index) in props.row.childrens"
                    :key="index"
                  >
                    <div class="subject-title">
                      {{ `${index + 1} .  `
                      }}<span v-html="item.question_detail.q_body" />
                      {{ `（${item.score}分）` }}
                    </div>
                    <!-- Single Multi -->
                    <div
                      class="subject-answers"
                      v-if="item.q_type == '单选' || item.q_type == '多选'"
                    >
                      <div
                        class="subject-answer"
                        v-for="(
                          aitem, aindex
                        ) in item.question_detail.q_items.split(';;')"
                        :key="aindex"
                      >
                        <span>{{
                          aitem | filterSMChoice(aindex, alphabet)
                        }}</span
                        ><span v-html="aitem"></span>
                      </div>
                      <div class="answer">
                        答案：
                        {{
                          item.q_right_answer
                            | filterSMultiAnswer(
                              item.question_detail.q_items,
                              alphabet
                            )
                        }}
                      </div>
                    </div>
                    <!-- Judge -->
                    <div class="subject-answers" v-if="item.q_type == '判断'">
                      <div class="subject-answer">
                        A.<el-radio label="1">对</el-radio> B.<el-radio
                          label="2"
                          >错</el-radio
                        >
                      </div>
                      <div class="answer">答案： {{ item.q_right_answer }}</div>
                    </div>
                    <!-- Fill -->
                    <div
                      class="subject-answers"
                      v-if="item.q_type == '选择填空'"
                    >
                      <div class="answer">
                        答案： {{ item.q_right_answer | filterFillAnswer }}
                      </div>
                    </div>
                    <!-- Linear -->
                    <div
                      class="subject-answers-linear"
                      v-if="item.q_type == '连线'"
                    >
                      <div class="subject-answer-left">
                        <div
                          class="subject-answer"
                          v-for="(aitem, aindex) in item.question_detail.q_items
                            .split('||')[0]
                            .split(';;')"
                          :key="'0-' + aindex"
                        >
                          {{ aitem }}
                        </div>
                      </div>
                      <div class="subject-answer-right">
                        <div
                          class="subject-answer"
                          v-for="(aitem, aindex) in item.question_detail.q_items
                            .split('||')[1]
                            .split(';;')"
                          :key="'1-' + aindex"
                        >
                          {{ aitem }}
                        </div>
                      </div>
                      <div class="answer">
                        答案：
                        {{
                          item.q_right_answer
                            | filterLinearAnswer(item.q_right_answer)
                        }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="changePage">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currPage"
          :page-sizes="[10, 20, 30, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next"
          :total="testLets.length"
        >
        </el-pagination>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {
  getQuestionGroupList,
  getQuestionList,
  getQuestionDetail,
} from "@/request/questionbank";
export default {
  data() {
    return {
      show: false,
      searchValue: "", // 搜索关键词
      // 搜索类型配置
      options: [
        // {
        //   value: 'HTML',
        //   label: 'HTML',
        // },
        // {
        //   value: 'CSS',
        //   label: 'CSS',
        // },
        // {
        //   value: 'JavaScript',
        //   label: 'JavaScript',
        // },
      ],
      // 选择的搜索类型
      selectType: [],
      // 题组列表
      testLets: [
        // {
        //   id: '12987142',
        //   name: '01 Python的数据类型',
        //   numberOfTimes: 1,
        //   state: '正常',
        //   childrens: [],
        // },
      ],
      // 题目列表
      questionList: [],
      // 选择的题组列表
      selectTestlet: null,
      // 字母排序
      alphabet: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ],
      currPage: 1,
      getRowKeys(row) {
        return row.gid;
      },
      expands: [],
    };
  },
  props: {
    showSelectTestlet: Boolean,
    foreignID: Number,
    questionGroupDetail: Object,
  },
  watch: {
    showSelectTestlet(n, o) {
      this.show = n;
      if (n) this.fetchQuestionGroupList();
      // if (n && !this.questionList.length) this.fetchQuestionList();
    },
    // questionGroupDetail(n, o) {
    //   // this.testLets.forEach()
    // },
    testLets(n, o) {
      // 找到已选择的行
      if (this.foreignID) {
        let findCurrRow = n.filter((item) => item.gid == this.foreignID);
        if (findCurrRow.length) this.$refs.table.setCurrentRow(findCurrRow[0]);
      }
    },
  },
  filters: {
    // 单选多选 选项顺序
    filterSMChoice(val, index, alphabet) {
      return alphabet[index] + ".";
    },
    // 填空 答案
    filterFillAnswer(val) {
      return val.split(";;").join("、");
    },
    // 单选、多选 答案
    filterSMultiAnswer(val, option, alphabet) {
      // 图片答案
      const ImgReg = /<img.*?src=["|']?(.*?)["|']?\s.*?>/i;
      if (ImgReg.test(option)) {
        return val;
      }
      let answer = "";
      val.split(";;").forEach((item, index) => {
        answer +=
          item +
          "：" +
          option.split(";;")[alphabet.indexOf(item)] +
          (index + 1 == val.split(";;").length ? "" : "、");
      });
      return answer;
    },
    // 连线 答案
    filterLinearAnswer(val) {
      let answer = "";
      let l = val.split("||")[0];
      let r = val.split("||")[1];
      l.split(";;").forEach((item, index) => {
        answer +=
          item +
          "-" +
          r.split(";;")[index] +
          (index + 1 !== l.split(";;").length ? "、" : "");
      });
      return answer;
    },
  },
  methods: {
    // 关闭弹窗
    handleClose() {
      this.$emit("close");
    },
    // 获取题组列表
    fetchQuestionGroupList() {
    debugger
      getQuestionGroupList().then((data) => {
        if (data) {
          data.map((item) => {
            this.$set(item, "childrens", []);
          });
          this.testLets = data;
        } else {
          this.$antdMessage.error({
            content: "获取题组失败！",
          });
        }
      });
    },
    // 获取所有题目
    fetchQuestionList() {
      getQuestionList().then((data) => {
        // if (res.errno === 0) {
          this.questionList = data;
        // }
      });
    },
    fetchQuestionDetail(data) {
      return new Promise((resolve, reject) => {
        getQuestionDetail(data)
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 保存题目
    handleSaveTestLet() {
      if (!this.selectTestlet) {
        this.$antdMessage.warning({
          content: "请选择题组，题组不能为空！",
        });
        return;
      }
      this.$emit("saveTestlet", this.selectTestlet);
    },
    // 选择
    handleSelectionChange(val) {
      this.selectTestlet = val;
    },
    // 监听展开
    async handleExpandChange(row, expandedRows) {
      let selectQuesList = row.question_list_json;
      if (typeof row.load === "undefined") {
        this.$set(row, "load", false);
      }

      let inArr = expandedRows.filter((item) => item.gid === row.gid);
      if (!inArr.length) return (row.load = false);

      if (row.load) {
        row.load = false;
      } else {
        row.childrens = []; // 删除旧数据
        row.load = true;
        for (let i = 0; i < selectQuesList.length; i++) {
          let res = await this.fetchQuestionDetail({
            id: selectQuesList[i].qid,
          });
          if (res.errno === 0) {
            this.$set(res.data, "score", selectQuesList[i].score);
            row.childrens.push(res.data);
          }
        }
        row.load = false;

        // let timer = setTimeout(() => {
        //   row.load = false;
        //   this.$set(row, "childrens", [
        //     {
        //       id: "12987129",
        //       name: "01 Python的数据类型",
        //       type: "连线",
        //       state: "正常",
        //       option: "XXXX;;AAAA;;BBBB",
        //       option2: "QQQQ;;DDDD;;NNNN",
        //       answer: "XXXX;;AAAA;;BBBB||QQQQ;;DDDD;;NNNN",
        //       score: 20,
        //     },
        //     {
        //       id: "12987129",
        //       name: "01 Python的数据类型",
        //       type: "单选",
        //       state: "正常",
        //       option: "XXXX;;AAAA;;BBBB;;DDDD;;QWEE;;XCZC",
        //       answer: "BBBB",
        //       score: 20,
        //     },
        //     {
        //       id: "12987129",
        //       name: "01 Python的数据类型",
        //       type: "多选",
        //       state: "正常",
        //       option:
        //         "XXXX;;AAAA;;BBBB;;VZXC;;QQQQ;;XXXX;;AAAA;;DDDD;;HERT;;NNNN;;BASD",
        //       answer: "QQQQ;;DDDD;;NNNN",
        //       score: 20,
        //     },
        //     {
        //       id: "12987129",
        //       name: "01 Python的数据类型",
        //       type: "判断",
        //       state: "正常",
        //       answer: "对",
        //       score: 20,
        //     },
        //     {
        //       id: "12987129",
        //       name: "01 Py__的__类型",
        //       type: "填空",
        //       state: "正常",
        //       answer: "QQQQ;;DDDD",
        //       score: 20,
        //     },
        //   ]);

        //   clearTimeout(timer);
        // }, 500);
      }
    },
    // 点击某一行
    handleRowClick(row, column, event) {
    },
    // 点击当前行
    handleCurrentRowChange(val) {
      this.selectTestlet = val;
    },
    // 每页展示条数
    handleSizeChange(val) {
    },
    // 切换页数
    handleCurrentChange(val) {
    },
  },
};
</script>

<style lang="stylus">
.selectTestletDialog {
  width: 90vw;
  max-width: 1200px;
  min-width: 980px;
  height: 650px;

  .el-dialog__header {
    padding-top: 43px;
    padding-bottom: 16px;
    text-align: center;

    .el-dialog__title {
      font-weight: bold;
      font-family: PMingLiU-ExtB;
      font-size: 22px;
      color: #0a0a0a;
    }

    .el-dialog__headerbtn {
      .el-icon-close {
        font-size: 25px;
        font-weight: bold;
        color: #0e79c0;
      }
    }
  }

  .el-dialog__body {
    padding: 20px 30px 0 37px;

    .container {
      width: 100%;
      height: 100%;

      .toolsBox {
        display: flex;
        justify-content: space-between;
        height: 40px;

        > div {
          display: flex;

          .newTestletBtn {
            width: 120px;
            height: 40px;
            background-color: #55a573;
            border-radius: 5px;
            font-family: Segoe UI;
            border: none;
            font-size: 16px;
            color: #ffffff;
          }

          .saveBtn {
            // margin-left: 50px;
            width: 120px;
            height: 40px;
            background-color: #0e79c0;
            border-radius: 5px;
            border: none;
            font-family: Segoe UI;
            font-size: 16px;
            color: #ffffff;
          }

          .selectBox {
            margin-left: 50px;

            .el-select {
              .el-input {
                .el-input__inner {
                  width: 180px;
                  height: 40px;
                  border-radius: 5px;
                  border: solid 1px #dcdbdb;
                }
              }
            }
          }
        }

        .searchInputBox {
          margin-left: 50px;
          display: flex;

          .searchInput {
            width: auto;

            .el-input__inner {
              width: 250px;
              height: 40px;
              border-radius: 5px;
              border: solid 1px #dcdbdb;
            }
          }

          .searchBtn {
            margin-left: 10px;
            display: block;
            padding: 0;
            width: 80px;
            height: 40px;
          }
        }
      }

      .testletList {
        margin-top: 20px;
        width: 100%;
        height: 100%;

        .el-table {
          .el-table__header-wrapper {
            .has-gutter {
              tr > th {
                border-left: none;
                border-right: none;
              }

              .cell {
                padding-left: 0;
                padding-right: 0;
              }
            }
          }

          .el-table__body-wrapper {
            overflow-y: auto;

            .el-table__body {
              tr > td {
                font-family: Segoe UI;
                font-size: 14px;
                color: #909090;
                border-left: none;
                border-right: none;

                .el-icon-arrow-right {
                  top: 0;
                  transform: rotate(90deg) translate(20%, 0);
                  font-size: 24px;
                  transition: all 0.2s linear;
                }

                .el-table__expand-icon--expanded {
                  transform: rotate(0);

                  .el-icon-arrow-right {
                    transform: rotate(180deg) translate(0, -15%);
                  }
                }
              }

              tr > .testTelName {
                font-weight: bold;
                color: #707070;
              }

              .el-table__row:hover {
                background-color: #fee9c5;

                .testTelName {
                  color: #fea91b;
                }
              }

              tr:hover>td {
                background-color: #fee9c5;

                .el-icon-arrow-right {
                  color: #fea91b;
                }
              }

              .el-table__expanded-cell {
                .subjectList {
                  .subject-title {
                    padding-bottom: 5px;
                    font-family: Segoe UI;
                    font-size: 14px;
                    color: #090909;
                  }

                  .subject-answers {
                    display: flex;
                    flex-flow: row wrap;

                    .subject-answer {
                      margin-right: 75px;
                      font-family: Segoe UI;
                      font-size: 14px;
                      color: #090909;

                      .el-radio {
                        .el-radio__input {
                          .el-radio__inner {
                            border-width: 4px;
                          }
                        }
                      }
                    }

                    .answer {
                      width: 100%;
                      font-family: Segoe UI;
                      font-size: 14px;
                      color: #feb53c;
                    }
                  }

                  .subject-answers-linear {
                    display: flex;
                    flex-flow: row wrap;

                    .subject-answer-left {
                      margin-right: 75px;
                      font-family: Segoe UI;
                      font-size: 14px;
                      color: #090909;
                    }

                    .subject-answer-right {
                      margin-right: 75px;
                      font-family: Segoe UI;
                      font-size: 14px;
                      color: #090909;
                      margin-left: 75px;
                    }

                    .answer {
                      width: 100%;
                      font-family: Segoe UI;
                      font-size: 14px;
                      color: #feb53c;
                    }
                  }
                }
              }
            }
          }
        }
      }

      .changePage {
        margin-top: 20px;
        text-align: center;
      }
    }
  }
}
</style>

